package com.liaoye.hellocustomview.view;

import android.animation.ValueAnimator;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.RectF;
import android.view.View;
import android.view.animation.LinearInterpolator;

public class AnimaWaveView extends View {

    private Path mPath;
    private Paint mPaint;
    private int mItemWaveLength = 1200;
    private float dx;

    public AnimaWaveView(Context context) {
        super(context);
        init();
        startAnima();
    }

    private void startAnima() {
        ValueAnimator animator = ValueAnimator.ofFloat(0, mItemWaveLength);
        animator.setDuration(2000);
        animator.setRepeatCount(ValueAnimator.INFINITE);
        animator.setInterpolator(new LinearInterpolator());
        animator.addUpdateListener(animation -> {
            dx = (float) animation.getAnimatedValue();
            postInvalidate();
        });
        animator.start();
    }

    private void init() {
        mPath = new Path();
        mPaint = new Paint();
        mPaint.setColor(Color.GREEN);
        mPaint.setStrokeWidth(2);
    }


    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        mPath.reset();

        int originY = 300;
        int halfWaveLen = mItemWaveLength / 2;
        mPath.moveTo(-mItemWaveLength + dx, originY);

        for (int i = -mItemWaveLength; i <= getWidth() + mItemWaveLength; i+=mItemWaveLength) {
            mPath.rQuadTo(halfWaveLen/2, -100, halfWaveLen, 0);
            mPath.rQuadTo(halfWaveLen/2, 100, halfWaveLen, 0);
        }
        mPath.lineTo(getWidth() + mItemWaveLength, getHeight());
        mPath.lineTo(-mItemWaveLength, getHeight());
        mPath.close();

        canvas.drawPath(mPath, mPaint);
    }
}
